package org.khd.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang.StringUtils;
import org.khd.gift.domain.User;
import org.khd.gift.exception.AssertException;
import org.khd.gift.exception.BusinessException;
import org.khd.gift.exception.ResponseCode;
import org.khd.gift.service.IUserService;
import org.khd.gift.service.IVerifyCodeService;
import org.khd.gift.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String USER_REGISTER_SMS_CODE = "user_register_sms_code";

    @Override
    public void userRegisterSendSmsCode(String phone) {
        // 1 参数校验
        // 1.1 校验当前手机号是否已注册，如果已经注册，返回错误信息
        Wrapper<User> userWrapper = new EntityWrapper<User>().eq("phone", phone);
        User user = userService.selectOne(userWrapper);
        AssertException.isNull(user, ResponseCode.RESPONSE_CODE_10020);

        //发送短信验证码
        String key = USER_REGISTER_SMS_CODE + phone;
        sendSmsCode(key);

    }

    @Override
    public String getSmsCode(String phone) {
        String key = USER_REGISTER_SMS_CODE + phone;

        // 从redis中获取当前手机号所对应的验证码
        String smsCode = (String)redisTemplate.opsForValue().get(key);
        AssertException.isNotBlank(smsCode, ResponseCode.RESPONSE_CODE_10018);
        return smsCode;
    }

    private void sendSmsCode(String key){
        //2 从redis中获取当前手机号所对应的验证码
        String smsCode = (String)redisTemplate.opsForValue().get(key);

        //3 如果redis中存在验证码
        if (StringUtils.isNotBlank(smsCode)) {
            //3.1 判断当前验证码有没有过重发时间 - key过期时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS); //key过期时间
            //3.2 如果没有过重发时间，返回错误信息；请不要频繁发送短信验证码
            //过期时间 > 4分钟(4*60)就说明还没有过重复时间
            if (expire > 4 * 60) {
                throw new BusinessException(ResponseCode.RESPONSE_CODE_10021);
            }
        }else {
                //4 如果redis中没有当前手机号的验证码
                //4.1 生成一个6位数的随机数
                smsCode = StrUtils.getRandomString(6);
            }

            //4.2 将它存入redis，并设置5分钟的过期时间
            redisTemplate.opsForValue().set(key,smsCode,5,TimeUnit.MINUTES);

            //4.3 发送短信给用户
            String msg = "您的短信验证码为" + smsCode + ",验证码将在5分钟后过期，请尽快填写";
            //SmsUtil.sendSms(dto.getPhone(),msg);
            System.out.println(msg);

        }

}
